#include <mysql.h>
#include <stdio.h>
#include <fcntl.h>

#include <string.h>
#include <stdlib.h>

#include <time.h>
#include <locale.h>
#include <langinfo.h>

#include <unistd.h>
#include <math.h>
#include <termios.h>

double get_cpu_temp()
{
	FILE *fp;
	char path[1035];
	double temp;

	fp = popen("./cputemp\0", "r");
	if (fp == NULL) {
		printf("Failed to run command\n" );
		exit;
	}

	while (fgets(path, sizeof(path)-1, fp) != NULL) {
		//printf("%s", path);
		temp = strtod(path, NULL);
	}
	pclose(fp);
	return temp;
}


MYSQL *prisijungti_db()
{
	MYSQL *conn;
	conn = mysql_init(NULL);
	char *server = "stud.if.ktu.lt";
	char *user = "mardrob";
	char *password = "test";
	char *database = "mardrob";
	/* Connect to database */
	if (!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0)) {
		fprintf(stderr, "%s\n", mysql_error(conn));
		exit(1);
	}
	return conn;
}

void generuoti_sin(MYSQL *conn, int HeaderNr, double f, int n)
{
	double temp;
	char eil[256];
	char diena[12], laikas[12];
	time_t seconds, seconds_offset;
	struct tm *tm = localtime(&seconds);
	char *dien="2010-01-01";
	memset (tm, 0, sizeof (*tm));
	strptime (dien, "%F", tm);
	seconds = mktime(tm);
	double dt = 60*60*24/n;
	
	seconds -= (60*60*24*1);
	seconds_offset = seconds;
	
	for (int i=0; i<n; i++){
		tm = localtime(&seconds);
		strftime(diena, sizeof(diena), "%F", tm);
		strftime(laikas, sizeof(laikas), "%T", tm);

		temp=sin(3.14159265358979323846*2*f*i)*12.6 - 20;// - drand48()*3;

		sprintf(eil, "INSERT INTO Log"
		  " VALUES (NULL, '%d', '%f', '%s %s');",
		  HeaderNr, temp, diena, laikas);
		printf("%s\n", eil, strlen(eil));
		seconds = seconds_offset + dt*i;
		//seconds += (mrand48()%40);

		/* send SQL query */
		if (mysql_query(conn, eil)) {
			fprintf(stderr, "%s\n", mysql_error(conn));
			exit(1);
		}
	}
}

void generuoti_rsin(MYSQL *conn, int HeaderNr, double f, int n)
{
	double temp;
	char eil[256];
	char diena[12], laikas[12];
	time_t seconds, seconds_offset;
	struct tm *tm = localtime(&seconds);
	char *dien="2010-01-01";
	memset (tm, 0, sizeof (*tm));
	strptime (dien, "%F", tm);
	seconds = mktime(tm);
	double dt = 60*60*24/n;
	
	seconds -= (60*60*24*1);
	seconds_offset = seconds;
	
	for (int i=0; i<n; i++){
		tm = localtime(&seconds);
		strftime(diena, sizeof(diena), "%F", tm);
		strftime(laikas, sizeof(laikas), "%T", tm);

		temp=sin(3.14159265358979323846*2*f*i)*12.6 - 20 - drand48()*3;

		sprintf(eil, "INSERT INTO Log"
		  " VALUES (NULL, '%d', '%f', '%s %s');",
		  HeaderNr, temp, diena, laikas);
		printf("%s\n", eil, strlen(eil));
		seconds = seconds_offset + dt*i;
		seconds += (mrand48()%40);

		/* send SQL query */
		if (mysql_query(conn, eil)) {
			fprintf(stderr, "%s\n", mysql_error(conn));
			exit(1);
		}
	}
}



int main() {
	//---- Terminalo nustatymai
	struct termios old_tio, new_tio;
	unsigned char c;

	/* get the terminal settings for stdin */
	tcgetattr(STDIN_FILENO,&old_tio);

	/* we want to keep the old setting to restore them a the end */
	new_tio=old_tio;

	/* disable canonical mode (buffered i/o) and local echo */
	new_tio.c_lflag &=(~ICANON & ~ECHO);
	new_tio.c_cc[VTIME]=0;
	new_tio.c_cc[VMIN]=0;

	/* set the new settings immediately */
	tcsetattr(STDIN_FILENO,TCSANOW,&new_tio);
	
	/* nebuferizuota išvestis */
	setvbuf ( stdout, NULL, _IONBF, 0);
//----
	
	
	printf("%-38s\r", "Jungiamės prie db...");
	MYSQL *conn = prisijungti_db();
	const int HeaderNr = 1001; //Pasirinktas duomenų antraštės nr.
	double f=(double)1/100;
	int n=100;



	//generuoti_sin(conn, HeaderNr, f, n);
	//generuoti_rsin(conn, HeaderNr, f, n);

	double temp;
	char eil[256];
	char diena[12], laikas[12];

	time_t seconds = time(NULL);
	struct tm *tm = localtime(&seconds);
	//seconds = mktime(tm);

	FILE* fd = fopen("./mat.dat", "w");
	printf("%-38s\r", "Paruošiama vieta duomenų bazėje...");
	if (mysql_query(conn, "delete from Log where HeaderNr=1001;")) {
		fprintf(stderr, "%s\n", mysql_error(conn));
		exit(1);
	}



//	for (int i=0; i<100; i++){
	do {
		seconds = time(NULL);
		tm = localtime(&seconds);
		strftime(diena, sizeof(diena), "%F", tm);
		strftime(laikas, sizeof(laikas), "%T", tm);
		temp = get_cpu_temp();

		sprintf(eil, "INSERT INTO Log"
		  " VALUES (NULL, '%d', '%f', '%s %s');",
		  HeaderNr, temp, diena, laikas);
		//printf("%s\n", eil, strlen(eil));

		printf("%-38s\r", "Siunčiam į duombazę ir failą");
		if (mysql_query(conn, eil)) {
			fprintf(stderr, "%s\n", mysql_error(conn));
			exit(1);
		}
		/* taip pat įrašom į failą */
		sprintf(eil, "%s-%s\t%f", diena, laikas, temp);
		fprintf(fd, "%s\n", eil, strlen(eil));
		
		sprintf(eil, "%.1f°C", temp);
		printf("%-38s\r",eil);
		sleep(1);
		c=getchar();
		if (c=='s')
			system("./start");
		else if (c=='t')
			system("./stop");
		
	} while(c!='q');
	


	fclose(fd);
	mysql_close(conn);

	system("cat timest");

	printf("%-38s\r", "Brėžiamas grafikas...");
	system("gnuplot gnuplots");

	
	/* restore the former settings */
	tcsetattr(STDIN_FILENO,TCSANOW,&old_tio);
}
